/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.zjdt.epserver.servlet.siter;

import com.zjdt.epserver.db.service4mysql.CargoServiceImpl;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileExistsException;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.dusin.web.util.JsonUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


/**
 *
 * @author dusin
 */
@WebServlet(name = "SiterUploadFile", urlPatterns = {"/servlet/siter/UploadFile"})
public class UploadFile extends HttpServlet {
    static Logger logger = Logger.getLogger(UploadFile.class);
    private CargoServiceImpl cargo;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");        

        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");
        }
        String jsonText=null;        
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Configure a repository (to ensure a secure temp location is used)
        
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        //System.out.println("repository:" + repository.getAbsolutePath());
        factory.setRepository(repository);
        ServletFileUpload uploadHandler = new ServletFileUpload(factory);
        uploadHandler.setHeaderEncoding("utf-8");  //可以解决中文文件名乱码问题
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        cargo = (CargoServiceImpl) context.getBean("cargoService");         
        String filename=null;
        String username=null;
        String recordNo=null;
        try {
            FileItem uploadFileItem = null;
            List<FileItem> items = uploadHandler.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    uploadFileItem = item;
                    filename = uploadFileItem.getName();
                } else {
                    if ("recordNo".equals(item.getFieldName())) {
                        recordNo = item.getString();
                        //recordNo = new String(recordNo.getBytes("ISO-8859-1"), "utf-8");                        
                    } else if("username".equals(item.getFieldName())){
                        username = item.getString();                        
                    }
                }
            }           
            File path = new File("./webapps/EPServer/photo/");
            System.out.println(path.getAbsoluteFile().toString());
            File file = new File(path.getCanonicalFile().toString(),filename); 
            
            
            //File file = new File(filename); 
            //System.out.println(file.getAbsoluteFile().toString());
            if(file.exists()){
                file.delete();
            }
            uploadFileItem.write(file);
            if(filename.startsWith("f")||filename.startsWith("头")){
                cargo.updatePhotoNameByRecordNo(recordNo, "frontPhoto", filename);
            }else if(filename.startsWith("s")||filename.startsWith("货")){
                cargo.updatePhotoNameByRecordNo(recordNo, "sidePhoto", filename);
            }else if(filename.startsWith("l")||filename.startsWith("证")){   //证件照l（L）
                cargo.updatePhotoNameByRecordNo(recordNo, "licensePhoto", filename);
            }else if(filename.startsWith("p")||filename.startsWith("单")){
                cargo.updatePhotoNameByRecordNo(recordNo, "paperPhoto", filename);
            }            
            logger.info("上传成功"+filename);
            jsonText = JsonUtil.createSuccessJsonResponse("上传成功");
            //备份图片文件
            File bakPath = new File("d:/ep/photobak/");
            FileUtils.copyFileToDirectory(file, bakPath);
        } catch (FileExistsException e) {
            jsonText = JsonUtil.createFailureJsonResponse("文件已存在");
            e.printStackTrace();
        } catch(IOException e){
            if(jsonText!=null&&!"".equals(jsonText)){
                
            }else{
                jsonText = JsonUtil.createFailureJsonResponse("文件IO错误");
            }
            e.printStackTrace();
        }
        catch (Throwable t) {
            jsonText = JsonUtil.createFailureJsonResponse("操作失败");
            t.printStackTrace();
        } finally {
            out.println(jsonText);
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
